/*
ofost46865

(需要的伤害-塔伤害 )/30*40

11t 6ra 10m 23h 


挖墙角策略
StationLab.boostAbleLevel(Game.rooms.W19N11,"upgradeController",15,1);

*/

require("main_mount");
// Object.values(Game.creeps).forEach(e=>e.suicide()).filter(e=>e.memory.role=='worker')
// _.values(Game.rooms).map(e=>e.find(FIND_CONSTRUCTION_SITES).filter(e=>e.structureType==STRUCTURE_ROAD)).flat().forEach(e=>e.remove())


Game.market.createOrder({
    type: ORDER_BUY,
    resourceType: PIXEL,
    price: 0.00001,
    totalAmount: 1,
});

let pro={
    init:function () {
        _.values(Game.rooms).forEach(room=> room.used={});
        HelperError.catchError(()=>ManagerCrossShard.init());
        HelperError.catchError(()=>ManagerMissions.init());// 依赖 ManagerCrossShard
        HelperError.catchError(()=>ManagerCreeps.init());
        HelperError.catchError(()=>ManagerFlags.init());
    },
    exec:function () {
        // _.values(Game.creeps).filter(e=>e.memory.role=="carrier").forEach(e=>e.memory.tasks = [])
        // _.values(Game.creeps).forEach(e=>e.sayHeadTask());
        // _.values(Game.creeps).forEach(e=>e.spawning||e.say(e.lastTask().taskName));
        // 注册
        // _.values(Game.creeps).forEach(e=>{try{e.execRegFun()}catch (exc) {log(e.memory.role)}});
        // _.values(Game.creeps).forEach(e=>{e.suicide()});
        _.values(Game.creeps).forEach(e=>HelperError.catchError(()=>e.execRegFun()));

        // 出击！
        HelperError.catchError(()=>StrategyAtkl2.exec());
        HelperError.catchError(()=>TeamRaL1.exec());

        // 配置资源
        _.values(Game.rooms).forEach(room=>HelperError.catchError(()=>(ManagerRooms.exec(room))));
        HelperError.catchError(()=>StrategyClaim.exec());
        HelperError.catchError(()=>StrategyClaimCrossShard.exec());
        HelperError.catchError(()=>StrategyScouter.exec());

        // 执行
        // _.values(Game.creeps).forEach(e=>{try{e.spawning||e.execLastTask()}catch (exc) {e.suicide()}});
        _.values(Game.creeps).forEach(e=>e.spawning||HelperError.catchError(()=>e.execLastTask()));


        HelperError.catchError(()=>ManagerAutoPlanner.exec());
    },
    afterWork:function(){
        HelperError.catchError(()=>ManagerCrossShard.afterWork());
    }
};



let main = function(){


    // let t = Game.cpu.getUsed()
    // console.log(Game.cpu.getUsed()-t)

    pro.init();
    pro.exec();
    pro.afterWork();

    try{if (Game.cpu.bucket >= 10000&&LOCAL_SHARD_NAME!="shard3")Game.cpu.generatePixel();}catch (e) {}
    if(Game.time%300==0){
        console.log(LOCAL_SHARD_NAME+" bucket : "+Game.cpu.bucket)
    }
    // Game.rooms.W14N21.terminal.send("machine",2,"E1S41")
    // if(LOCAL_SHARD_NAME=="shard3"&&Game.time%10==0&&Game.rooms.W14N21&&Game.rooms.W14N21.my){
    //     Game.rooms.W14N21.terminal.send("H",3000,"W17N19")
    // }
    // if(LOCAL_SHARD_NAME=="Screeps.Cc"&&Game.time%10==0&&Game.rooms.W5N8&&Game.rooms.W5N8.my){
    //     Game.market.deal("60994d0d37b48a557434dbd7",3000,"W5N8")
    // }
    HelperError.throwAllError();
};

global.main = pro;

// module.exports.loop=require("调用栈分析器").warpLoop(main);
module.exports.loop=main;






function tmp(){
    Game.rooms.W5N8.nuker.launchNuke(new RoomPosition(20,12,"W3N6"))
    Game.rooms.W18N16.terminal.send(RESOURCE_ENERGY,40000,"W19N21")
    // Game.market.orders;
    (()=>{
        let myRoom = "W19N21";
        let orders = Game.market.getAllOrders({type: ORDER_SELL, resourceType: "Z"});
        let minPrice = 0.6;
        let minOrder = undefined;
        for(let order of orders){
            let energyNeed = Game.market.calcTransactionCost(order.remainingAmount,myRoom,order.roomName);
            let totalPrice = energyNeed*0.5 +order.remainingAmount*order.price;
            let price = totalPrice/order.remainingAmount;
            if(price<minPrice){
                minOrder = order;
                minPrice=price;
            }
        }
        if(minOrder){
            let code = Game.market.deal(minOrder.id,minOrder.remainingAmount,myRoom);
            log(minOrder.remainingAmount,minPrice,minOrder.id,code);
        }
    })()

    if(LOCAL_SHARD_NAME=="shard2"&&Game.rooms.W14N21&&Game.time%10==0){
        Game.rooms.W14N21.terminal.send("H",3000,"W17N19")
    }


    _.values(Game.creeps).filter(e=>e.memory.role == "AttackerPB").forEach(e=>e.suicide())

    for(let rm of _.values(Memory.rooms)){
        _.values(rm[StationSources.stationName]).forEach(data=>{
            if(data["carryCreeps"])
                data["carryCreeps"] = data["carryCreeps"].filter(e=>Game.getObjectById(e))
        })
    }
    JSON.stringify(Memory)


    Game.market.createOrder({
        type: ORDER_SELL,
        resourceType: "X",
        price: 2.56,
        totalAmount: 50000,
        roomName:"W19N21"
    });

    Game.market.createOrder({
        type: ORDER_SELL,
        resourceType: "L",
        price: 0.179,
        totalAmount: 30000,
        roomName:"W22N19"
    });

    Game.market.createOrder({
        type: ORDER_SELL,
        resourceType: "H",
        price: 0.47,
        totalAmount: 30000,
        roomName:"W19N11"
    });

    Game.market.createOrder({
        type: ORDER_SELL,
        resourceType: "U",
        price: 0.349,
        totalAmount: 10000,
        roomName:"W19N23"
    });

    Game.market.createOrder({
        type: ORDER_SELL,
        resourceType: "energy",
        price: 0.2489,
        totalAmount: 150000,
        roomName:"W18N16"
    });

    Game.market.createOrder({
        type: ORDER_BUY,
        resourceType: PIXEL,
        price: 0.001,
        totalAmount: 1000,
    });

    Game.market.createOrder({
        type: ORDER_BUY,
        resourceType: RESOURCE_POWER,
        price: 0.001,
        totalAmount: 90000,
        roomName: "W18N16",
    });

    Game.market.deal("6092671835d3311a507e8ad4",1800,"W19N23")

    Game.market.deal("6078520ae489055ce2891534",30000,"W19N21")

    Game.market.deal("607c4b5a7946f476eb63789b",513)

    ManagerCrossShard.addCrossShardRequest("shard2",1111)

    // 检测内存泄漏
    // let memory = Math.round(Game.cpu.getHeapStatistics().used_heap_size/Game.cpu.getHeapStatistics().total_heap_size*100);
    // let str = ""
    // for(let i=0;i<100;i++){
    //     str+=(memory>=i?"▓":"_")
    // }

    ManagerCrossShard.addCrossShardRequest("shard3",{
        func:"test",
        callback:"updateFlag",
        data: {
            spawnRoom:"W19N21",
            body:pro.raBody,
            role:"raL1",
            tasks:[
                UtilsTask.taskData("boostCreepBodyPart","registerBoostCreep",{data:pro.raBoost})
            ],
        }
    })

    Game.market.createOrder({
        type: ORDER_BUY,
        resourceType: RESOURCE_ENERGY,
        price: 0.47,
        totalAmount: 100000,
        roomName: "W19N21",
    });

    _.values(Game.creeps).filter(e=>e.memory.role =="PBCarrier").forEach(e=>e.suicide())

    Game.rooms.W8N8.find(FIND_STRUCTURES).forEach(e=>e.destroy());
    Game.rooms.E9N24.find(FIND_STRUCTURES).filter(e=>e.structureType==STRUCTURE_ROAD).forEach(e=>e.destroy());
    Game.rooms.W8N8.find(FIND_CONSTRUCTION_SITES).forEach(e=>e.remove());
    Game.rooms.E12N9.find(FIND_CONSTRUCTION_SITES).forEach(e=>e.remove());
    Game.rooms.W1N1.find(FIND_CONSTRUCTION_SITES).forEach(e=>e.remove());
    Game.rooms.W1N1.find(FIND_STRUCTURES).forEach(e=>e.destroy());

    Game.cpu.bucket+" "+Game.cpu.getUsed()
}

